#include "texteditor.h"
#include "tabledialog.h"
#include <QTextDocument>
#include <QTextBlock>
#include <QMessageBox>
#include <QImage>
#include <QPixmap>
#include <QTextDocumentFragment>
#include <QImageReader>
#include <QFileDialog>
#include <QDebug>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFrame>
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#include <QStandardPaths>
#include <QBuffer>

#include <QTextDocument>
#include <QFile>
#include <QTextStream>
#include <QBuffer>
#include <QImageWriter>
#include <QRegularExpression>
#include <cmath>
#include <QApplication>
#include <QScreen>
#include <QPainter>
#include <QDateTime>

// 表格信息结构体
struct TableInfo {
    QVector<double> columnWidths;  // 列宽（毫米）
    QVector<double> rowHeights;    // 行高（毫米）
    int rows;
    int columns;

    TableInfo() : rows(0), columns(0) {}

    TableInfo(int r, int c) : rows(r), columns(c) {
        columnWidths.resize(c);
        rowHeights.resize(r);
        // 设置默认值（毫米）
        for (int i = 0; i < c; i++) {
            columnWidths[i] = 26.0; // 26mm
        }
        for (int i = 0; i < r; i++) {
            rowHeights[i] = 7.9; // 7.9mm
        }
    }
};

TextEditor::TextEditor(QWidget *parent)
    : QWidget(parent)
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0); // 外部边距
    mainLayout->setSpacing(0);

    // 创建QFrame容器来包装toolbar和textEdit
    editorFrame = new QFrame(this);
    editorFrame->setFrameStyle(QFrame::Box | QFrame::Plain);
    editorFrame->setLineWidth(1);

    // 设置QFrame的样式，模拟textEdit的边框
    editorFrame->setStyleSheet(
        "QFrame {"
        "    border: 1px solid #a0a0a0;"
        "    background-color: white;"
        "}"
    );

    // 创建QFrame内部的垂直布局
    QVBoxLayout *frameLayout = new QVBoxLayout(editorFrame);
    frameLayout->setContentsMargins(0, 0, 0, 0); // 移除内部边距
    frameLayout->setSpacing(0); // 移除间距

    // 创建工具栏
    setupToolbar();

    // 创建文本编辑器
    textEdit = new ResizableImageTextEdit(editorFrame);

    // 设置textEdit样式，完全隐藏边框
    textEdit->setStyleSheet(
        "QTextEdit {"
        "    border: none;" // 完全隐藏边框
        "    background-color: transparent;" // 透明背景
        "    selection-background-color: #3399ff;"
        "}"
    );

    // 将工具栏和文本编辑器添加到frame布局中
    frameLayout->addWidget(toolBar);
    frameLayout->addWidget(textEdit);

    // 将frame添加到主布局
    mainLayout->addWidget(editorFrame);

    // 设置布局
    setLayout(mainLayout);

    // 连接信号
    connect(textEdit, &QTextEdit::cursorPositionChanged, this, &TextEditor::updateTableResizeControls);
    connect(textEdit, &QTextEdit::selectionChanged, this, &TextEditor::updateTableResizeControls);

    // 连接文档内容变化信号来检测表格删除
    connect(textEdit->document(), &QTextDocument::contentsChanged, this, &TextEditor::onDocumentContentsChanged);

    // 设置合理的初始大小
    resize(800, 600);
    setWindowTitle("富文本编辑器");
    updateTableResizeControls();
    m_dpi = QApplication::primaryScreen()->logicalDotsPerInch();
    qDebug() << m_dpi << "m_dpi";
    QScreen *screen = QApplication::primaryScreen();
    qDebug() << "Logical DPI:" << screen->logicalDotsPerInch();
    qDebug() << "Physical DPI:" << screen->physicalDotsPerInch();
}

TextEditor::~TextEditor()
{
}

void TextEditor::setupToolbar()
{
    // 创建工具栏
    toolBar = new QToolBar(editorFrame);
    toolBar->setMovable(false);
    toolBar->setFloatable(false);
    toolBar->setIconSize(QSize(20, 20));

    // 设置工具栏样式，使其与textEdit无缝连接
    toolBar->setStyleSheet(
        "QToolBar {"
        "    background-color: #f8f8f8;"
        "    border: none;" // 隐藏工具栏边框
        "    border-bottom: 1px solid #d0d0d0;" // 只保留底部分隔线
        "    padding: 4px;"
        "    spacing: 2px;"
        "}"
        "QToolBar::separator {"
        "    background-color: #d0d0d0;"
        "    width: 1px;"
        "    margin: 2px 4px;"
        "}"
        "QToolButton {"
        "    border: 1px solid transparent;"
        "    border-radius: 3px;"
        "    padding: 3px;"
        "    margin: 1px;"
        "    background-color: transparent;"
        "}"
        "QToolButton:hover {"
        "    background-color: #e0e0e0;"
        "    border: 1px solid #c0c0c0;"
        "}"
        "QToolButton:pressed {"
        "    background-color: #d0d0d0;"
        "    border: 1px solid #a0a0a0;"
        "}"
        "QDoubleSpinBox {"
        "    border: 1px solid #c0c0c0;"
        "    border-radius: 2px;"
        "    padding: 2px;"
        "    background-color: white;"
        "    max-width: 80px;"
        "}"
        "QDoubleSpinBox:focus {"
        "    border-color: #0078d4;"
        "}"
    );

    setupToolbarActions();
}

void TextEditor::setupToolbarActions()
{
    // 左对齐按钮
    leftAlignAction = toolBar->addAction(QIcon::fromTheme("format-justify-left"), "");
    leftAlignAction->setToolTip("左对齐");
    connect(leftAlignAction, &QAction::triggered, this, &TextEditor::alignLeft);

    // 居中对齐按钮
    centerAlignAction = toolBar->addAction(QIcon::fromTheme("format-justify-center"), "");
    centerAlignAction->setToolTip("居中对齐");
    connect(centerAlignAction, &QAction::triggered, this, &TextEditor::alignCenter);

    // 右对齐按钮
    rightAlignAction = toolBar->addAction(QIcon::fromTheme("format-justify-right"), "");
    rightAlignAction->setToolTip("右对齐");
    connect(rightAlignAction, &QAction::triggered, this, &TextEditor::alignRight);

    // 分隔符
    toolBar->addSeparator();

    // 插入图片按钮
    insertImageAction = toolBar->addAction(QIcon::fromTheme("insert-image"), "");
    insertImageAction->setToolTip("插入图片");
    connect(insertImageAction, &QAction::triggered, this, &TextEditor::insertImage);

    // 插入表格按钮
    insertTableAction = toolBar->addAction(QIcon::fromTheme("insert-table"), "");
    insertTableAction->setToolTip("插入表格");
    connect(insertTableAction, &QAction::triggered, this, &TextEditor::insertTable);

    // 添加导出HTML按钮
   exportHtmlAction = new QAction(QIcon::fromTheme("document-export"), "提交", this);
   exportHtmlAction->setToolTip("将内容导出为HTML文件");
   toolBar->addAction(exportHtmlAction);
   connect(exportHtmlAction, &QAction::triggered, this, [this](){
       QString filePath = "output.html";
       saveRichTextToHtmlWithBase64(textEdit, filePath);
   });

   // 添加导入HTML按钮
   importHtmlAction = new QAction(QIcon::fromTheme("document-import"), "读取", this);
   importHtmlAction->setToolTip("从HTML文件读取内容");
   toolBar->addAction(importHtmlAction);
   connect(importHtmlAction, &QAction::triggered, this, [this](){//lbh
       QString filePath = "output.html";
           QFile file(filePath);
           if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
               qDebug() << "Failed to open file.";
               return false;
           }

       QString htmlContent = QTextStream(&file).readAll();
       QString outputImagePath = "./";
       QVector<ImageInfo> imageinfo;
       QVector<ParsedTableInfo> tableinfo; // 新增表格信息容器
       parseHtmlWithImagesAndTables(htmlContent, outputImagePath, imageinfo, tableinfo, 20);
   });

    // 添加分隔符
    toolBar->addSeparator();

    // 创建表格调整控件
    setupTableResizeControls();
    toolBar->addWidget(tableResizeWidget);
}

void TextEditor::setupTableResizeControls()
{
    // 创建表格调整控件容器
    tableResizeWidget = new QWidget(toolBar);
    QHBoxLayout *layout = new QHBoxLayout(tableResizeWidget);
    layout->setContentsMargins(5, 0, 5, 0);
    layout->setSpacing(8);

    // 列宽控件
    columnWidthLabel = new QLabel(tableResizeWidget);
    columnWidthLabel->setPixmap(QIcon::fromTheme("view-grid").pixmap(16, 16));
    columnWidthLabel->setToolTip("列宽");

    // 创建双精度微调框以支持小数
    columnWidthSpinBox = new QDoubleSpinBox(tableResizeWidget);
    columnWidthSpinBox->setRange(1.0, 1000.0); // 1mm到100mm
    columnWidthSpinBox->setValue(26.0); // 默认值26mm（约等于100px）
    columnWidthSpinBox->setSuffix(" mm");
    columnWidthSpinBox->setDecimals(2); // 保留两位小数
    columnWidthSpinBox->setSingleStep(0.1); // 每次点击增减0.1mm
    columnWidthSpinBox->setMaximumWidth(80);
    columnWidthSpinBox->setMinimumWidth(70);
    columnWidthSpinBox->setToolTip("列宽 (mm)");
    // 连接值改变的信号
    connect(columnWidthSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &TextEditor::applyTableResize);

    // 行高控件
    rowHeightLabel = new QLabel(tableResizeWidget);
    rowHeightLabel->setPixmap(QIcon::fromTheme("view-list-details").pixmap(16, 16));
    rowHeightLabel->setToolTip("行高");

    // 创建双精度微调框以支持小数
    rowHeightSpinBox = new QDoubleSpinBox(tableResizeWidget);
    rowHeightSpinBox->setRange(1.0, 100.0); // 1mm到100mm
    rowHeightSpinBox->setValue(7.9); // 默认值7.9mm（约等于30px）
    rowHeightSpinBox->setSuffix(" mm");
    rowHeightSpinBox->setDecimals(2); // 保留两位小数
    rowHeightSpinBox->setSingleStep(0.1); // 每次点击增减0.1mm
    rowHeightSpinBox->setMaximumWidth(80);
    rowHeightSpinBox->setMinimumWidth(70);
    rowHeightSpinBox->setToolTip("行高 (mm)");
    // 连接值改变的信号
    connect(rowHeightSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &TextEditor::applyTableResize);

    // 添加控件到布局
    layout->addWidget(columnWidthLabel);
    layout->addWidget(columnWidthSpinBox);
    layout->addWidget(rowHeightLabel);
    layout->addWidget(rowHeightSpinBox);
    layout->addStretch(); // 添加弹性空间

    tableResizeWidget->setLayout(layout);
}

void TextEditor::updateTableResizeControls()
{
    // 检查当前是否在表格内
    bool inTable = (getSelectedTable() != nullptr);

    // 启用或禁用表格调整控件
    columnWidthLabel->setEnabled(inTable);
    columnWidthSpinBox->setEnabled(inTable);
    rowHeightLabel->setEnabled(inTable);
    rowHeightSpinBox->setEnabled(inTable);

    // 如果在表格内，检查是否是多选
    if (inTable) {
        QTextTable *table = getSelectedTable();
        bool hasSelection = textEdit->textCursor().hasSelection();

        if (hasSelection) {
            // 如果是多选状态，设置提示信息
            columnWidthSpinBox->setToolTip("将设置所有选中列的宽度");
            rowHeightSpinBox->setToolTip("将设置所有选中行的高度");
        } else {
            // 单选状态，恢复正常工具提示
            columnWidthSpinBox->setToolTip("列宽 (mm)");
            rowHeightSpinBox->setToolTip("行高 (mm)");

            // 显示当前单元格的值
            int currentCol = getCurrentTableColumn();
            int currentRow = getCurrentTableRow();

            if (table && currentCol != -1 && tableInfoMap.contains(table)) {
                // 从映射中获取列宽信息（毫米）
                const TableInfo &info = tableInfoMap[table];
                if (currentCol < info.columnWidths.size()) {
                    double widthInMm = info.columnWidths[currentCol];
                    columnWidthSpinBox->blockSignals(true);
                    columnWidthSpinBox->setValue(widthInMm);
                    columnWidthSpinBox->blockSignals(false);
                }
            }

            // 显示当前行高（毫米）
            if (table && currentRow != -1 && tableInfoMap.contains(table)) {
                const TableInfo &info = tableInfoMap[table];
                if (currentRow < info.rowHeights.size()) {
                    double heightInMm = info.rowHeights[currentRow];
                    rowHeightSpinBox->blockSignals(true);
                    rowHeightSpinBox->setValue(heightInMm);
                    rowHeightSpinBox->blockSignals(false);
                }
            }
        }
    }
}

void TextEditor::onDocumentContentsChanged()
{
    // 检查是否有表格被删除
    cleanupDeletedTables();
}

void TextEditor::cleanupDeletedTables()
{
    // 收集文档中当前存在的所有表格
    QSet<QTextTable*> currentTables;
    QTextFrame* rootFrame = textEdit->document()->rootFrame();
    QTextFrame::iterator it;

    for (it = rootFrame->begin(); !it.atEnd(); ++it) {
        QTextFrame* childFrame = it.currentFrame();
        if (childFrame) {
            QTextTable* table = qobject_cast<QTextTable*>(childFrame);
            if (table) {
                currentTables.insert(table);
            }
        }
    }

    // 找出已删除的表格并从映射中移除
    QMutableMapIterator<QTextTable*, TableInfo> mapIt(tableInfoMap);
    while (mapIt.hasNext()) {
        mapIt.next();
        if (!currentTables.contains(mapIt.key())) {
            qDebug() << "Removing deleted table from map";
            mapIt.remove();
        }
    }
}

void TextEditor::alignLeft()
{
    textEdit->setAlignment(Qt::AlignLeft);
}

void TextEditor::alignCenter()
{
    textEdit->setAlignment(Qt::AlignCenter);
}

void TextEditor::alignRight()
{
    textEdit->setAlignment(Qt::AlignRight);
}

void TextEditor::insertImage()
{
    // 打开文件对话框选择图片
    QString filePath = QFileDialog::getOpenFileName(this,
        "选择图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)");

    if (!filePath.isEmpty()) {
        QImage image(filePath);
        if (image.isNull()) {
            QMessageBox::warning(this, "错误", "无法加载图片！");
            return;
        }

        // 自动换行后插入图片
        QTextCursor cursor = textEdit->textCursor();
        cursor.insertBlock();

        // 创建图片格式并设置大小
        QTextImageFormat imageFormat;
        imageFormat.setName(filePath);

        // 设置初始图片大小，但最大宽度不超过编辑器宽度的70%
        int maxWidth = textEdit->width() * 0.7;
        if (image.width() > maxWidth) {
            double ratio = (double)maxWidth / image.width();
            imageFormat.setWidth(maxWidth);
            imageFormat.setHeight(image.height() * ratio);
        } else {
            imageFormat.setWidth(image.width());
            imageFormat.setHeight(image.height());
        }

        // 插入图片
        cursor.insertImage(imageFormat);
        cursor.insertBlock();
    }
}

void TextEditor::insertTable()
{
    TableDialog dialog(this);
    dialog.move(cursor().pos());
    if (dialog.exec() == QDialog::Accepted) {
        int rows = dialog.rows();
        int columns = dialog.columns();

        QTextCursor cursor = textEdit->textCursor();

        // 在表格前自动换行
        cursor.insertBlock();

        // 设置对齐方式为靠左
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignLeft);
        cursor.setBlockFormat(blockFormat);

        // 插入表格并设置格式
        QTextTableFormat tableFormat;
        tableFormat.setBorder(1);
        tableFormat.setCellPadding(5); // 设置合理的内边距
        tableFormat.setCellSpacing(0);
        tableFormat.setAlignment(Qt::AlignLeft);

        // 设置等宽列 (默认26mm ≈ 100px)
        QVector<QTextLength> columnWidths;
        for (int i = 0; i < columns; i++) {
            // 将毫米转换为像素 (1mm ≈ 3.779px)
            columnWidths.append(QTextLength(QTextLength::FixedLength, 26.0 * 3.779));
        }
        tableFormat.setColumnWidthConstraints(columnWidths);

        QTextTable *table = cursor.insertTable(rows, columns, tableFormat);

        // 创建表格信息并添加到映射（以毫米为单位存储）
        TableInfo tableInfo(rows, columns);
        tableInfoMap[table] = tableInfo;

        qDebug() << "Added new table to map with" << rows << "rows and" << columns << "columns (stored in mm)";

        // 默认行高 (7.9mm ≈ 30px)
        double defaultRowHeightMm = 7.9;
        int defaultRowHeightPx = defaultRowHeightMm * 3.779;

        // 设置每个单元格的格式
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < columns; ++col) {
                QTextTableCell cell = table->cellAt(row, col);

                // 设置单元格格式
                QTextTableCellFormat cellFormat = cell.format().toTableCellFormat();

                // 设置单元格的最小高度
                cellFormat.setProperty(QTextFormat::TableCellRowSpan, 1);
                cellFormat.setProperty(QTextFormat::TableCellColumnSpan, 1);

                // 通过设置上下内边距来控制行高，但保持可编辑性
                int verticalPadding = (defaultRowHeightPx - 20) / 2; // 20是大概的字体高度
                if (verticalPadding < 2) verticalPadding = 2;

                cellFormat.setTopPadding(verticalPadding);
                cellFormat.setBottomPadding(verticalPadding);
                cellFormat.setLeftPadding(5);
                cellFormat.setRightPadding(5);

                cell.setFormat(cellFormat);

                // 设置文本块格式
                QTextCursor cellCursor = cell.firstCursorPosition();
                QTextBlockFormat cellBlockFormat;
                cellBlockFormat.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // 垂直居中
                cellCursor.setBlockFormat(cellBlockFormat);
            }
        }

        // 在表格后自动换行
        cursor = table->cellAt(rows-1, columns-1).lastCursorPosition();
        cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
        cursor.insertBlock();
        textEdit->setTextCursor(cursor);

        // 更新控件状态
        updateTableResizeControls();
    }
}

void TextEditor::applyTableResize()
{
    QTextTable *table = getSelectedTable();

    if (table && tableInfoMap.contains(table)) {
        // 获取当前选区信息
        QTextCursor cursor = textEdit->textCursor();
        int selectionStart = cursor.selectionStart();
        int selectionEnd = cursor.selectionEnd();

        // 记住当前光标位置
        QTextCursor originalCursor = cursor;

        // 查找选区覆盖的所有行和列
        QVector<int> selectedRows;
        QVector<int> selectedColumns;

        // 确定选区中的行和列
        if (cursor.hasSelection()) {
            // 先确定起始单元格
            int startRow = -1, startCol = -1;
            int endRow = -1, endCol = -1;

            // 查找起始单元格
            for (int row = 0; row < table->rows(); ++row) {
                for (int col = 0; col < table->columns(); ++col) {
                    QTextTableCell cell = table->cellAt(row, col);
                    if (selectionStart >= cell.firstPosition() && selectionStart <= cell.lastPosition()) {
                        startRow = row;
                        startCol = col;
                        break;
                    }
                }
                if (startRow != -1) break;
            }

            // 查找结束单元格
            for (int row = 0; row < table->rows(); ++row) {
                for (int col = 0; col < table->columns(); ++col) {
                    QTextTableCell cell = table->cellAt(row, col);
                    if (selectionEnd >= cell.firstPosition() && selectionEnd <= cell.lastPosition()) {
                        endRow = row;
                        endCol = col;
                        break;
                    }
                }
                if (endRow != -1) break;
            }

            // 如果找到了起始和结束单元格，收集所有选中的行和列
            if (startRow != -1 && endRow != -1) {
                int minRow = qMin(startRow, endRow);
                int maxRow = qMax(startRow, endRow);
                int minCol = qMin(startCol, endCol);
                int maxCol = qMax(startCol, endCol);

                // 收集所有选中的行
                for (int row = minRow; row <= maxRow; ++row) {
                    if (!selectedRows.contains(row)) {
                        selectedRows.append(row);
                    }
                }

                // 收集所有选中的列
                for (int col = minCol; col <= maxCol; ++col) {
                    if (!selectedColumns.contains(col)) {
                        selectedColumns.append(col);
                    }
                }
            }
        }

        // 如果没有选中多个单元格，退回到单行单列模式
        if (selectedRows.isEmpty() || selectedColumns.isEmpty()) {
            int currentRow = getCurrentTableRow();
            int currentCol = getCurrentTableColumn();

            if (currentRow != -1) {
                selectedRows.append(currentRow);
            }

            if (currentCol != -1) {
                selectedColumns.append(currentCol);
            }
        }

        // 只有在有选择的行和列时才进行调整
        if (!selectedRows.isEmpty() && !selectedColumns.isEmpty()) {
            // 获取表格信息
            TableInfo &tableInfo = tableInfoMap[table];

            // 1. 应用列宽 - 调整所有选中的列
            double columnWidthMm = columnWidthSpinBox->value();
            // 将毫米转换为像素 (1mm ≈ 3.779px)
            int columnWidthPx = columnWidthMm * 3.779;

            // 更新映射中的列宽信息（以毫米为单位存储）
            foreach (int col, selectedColumns) {
                if (col >= 0 && col < tableInfo.columnWidths.size()) {
                    tableInfo.columnWidths[col] = columnWidthMm;  // 存储毫米值
                }
            }

            // 应用到表格格式（以像素为单位）
            QTextTableFormat tableFormat = table->format();
            QVector<QTextLength> columnWidths;
            if (tableFormat.hasProperty(QTextFormat::TableColumnWidthConstraints)) {
                columnWidths = tableFormat.columnWidthConstraints();
            } else {
                for (int i = 0; i < table->columns(); ++i) {
                    columnWidths.append(QTextLength(QTextLength::PercentageLength, 100.0 / table->columns()));
                }
            }

            // 更新所有选中列的宽度
            bool columnWidthChanged = false;
            foreach (int col, selectedColumns) {
                if (col >= 0 && col < columnWidths.size()) {
                    columnWidths[col] = QTextLength(QTextLength::FixedLength, columnWidthPx);
                    columnWidthChanged = true;
                }
            }

            // 只有在列宽发生变化时才应用新的表格格式
            if (columnWidthChanged) {
                tableFormat.setColumnWidthConstraints(columnWidths);
                table->setFormat(tableFormat);
            }

            // 2. 应用行高 - 调整所有选中的行
            double rowHeightMm = rowHeightSpinBox->value();
            // 将毫米转换为像素 (1mm ≈ 3.779px)
            int rowHeightPx = rowHeightMm * 3.779;

            // 更新映射中的行高信息（以毫米为单位存储）
            foreach (int row, selectedRows) {
                if (row >= 0 && row < tableInfo.rowHeights.size()) {
                    tableInfo.rowHeights[row] = rowHeightMm;  // 存储毫米值
                }
            }

            // 遍历所有选中的行
            foreach (int row, selectedRows) {
                if (row >= 0 && row < table->rows()) {
                    // 修改当前行的所有单元格
                    for (int col = 0; col < table->columns(); ++col) {
                        QTextTableCell cell = table->cellAt(row, col);

                        // 获取当前单元格格式
                        QTextTableCellFormat cellFormat = cell.format().toTableCellFormat();

                        // 计算新的内边距来达到目标行高
                        // 估算字体高度
                        QTextCursor cellCursor = cell.firstCursorPosition();
                        QFontMetrics fm(cellCursor.charFormat().font());
                        int fontHeight = fm.height();

                        // 计算需要的垂直内边距
                        int totalVerticalPadding = rowHeightPx - fontHeight;
                        if (totalVerticalPadding < 4) totalVerticalPadding = 4; // 最小内边距

                        int topPadding = totalVerticalPadding / 2;
                        int bottomPadding = totalVerticalPadding - topPadding;

                        // 设置新的内边距
                        cellFormat.setTopPadding(topPadding);
                        cellFormat.setBottomPadding(bottomPadding);
                        cellFormat.setLeftPadding(5);  // 保持左右内边距不变
                        cellFormat.setRightPadding(5);

                        // 应用格式
                        cell.setFormat(cellFormat);

                        // 确保文本垂直居中
                        QTextBlock block = cellCursor.block();
                        while (block.position() < cell.lastPosition() && block.isValid()) {
                            QTextCursor blockCursor(block);
                            QTextBlockFormat blockFormat = block.blockFormat();
                            blockFormat.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                            blockCursor.setBlockFormat(blockFormat);
                            block = block.next();
                        }
                    }
                }
            }

            // 恢复原始光标位置
            textEdit->setTextCursor(originalCursor);

            qDebug() << "Updated table info in map for table with" << tableInfo.rows << "rows and" << tableInfo.columns << "columns (values stored in mm)";
        }
    }
}

bool TextEditor::hasTableSelection()
{
    QTextTable *table = getSelectedTable();
    if (!table) return false;

    QTextCursor cursor = textEdit->textCursor();
    return cursor.hasSelection();
}

int TextEditor::getCurrentTableRow()
{
    QTextTable *table = getSelectedTable();
    if (!table) return -1;

    QTextCursor cursor = textEdit->textCursor();

    // 获取当前光标所在的单元格
    for (int row = 0; row < table->rows(); ++row) {
        for (int col = 0; col < table->columns(); ++col) {
            QTextTableCell cell = table->cellAt(row, col);
            int cellStartPos = cell.firstPosition();
            int cellEndPos = cell.lastPosition();

            // 检查光标是否在当前单元格内
            if (cursor.position() >= cellStartPos && cursor.position() <= cellEndPos) {
                return row;
            }
        }
    }

    return -1;
}

int TextEditor::getCurrentTableColumn()
{
    QTextTable *table = getSelectedTable();
    if (!table) return -1;

    QTextCursor cursor = textEdit->textCursor();

    // 获取当前光标所在的单元格
    for (int row = 0; row < table->rows(); ++row) {
        for (int col = 0; col < table->columns(); ++col) {
            QTextTableCell cell = table->cellAt(row, col);
            int cellStartPos = cell.firstPosition();
            int cellEndPos = cell.lastPosition();

            // 检查光标是否在当前单元格内
            if (cursor.position() >= cellStartPos && cursor.position() <= cellEndPos) {
                return col;
            }
        }
    }

    return -1;
}

QTextTable *TextEditor::getSelectedTable()
{
    QTextCursor cursor = textEdit->textCursor();
    return cursor.currentTable();
}

int TextEditor::calculateCurrentRowHeight(const QTextTableCell &cell)
{
    // 获取单元格格式
    QTextTableCellFormat cellFormat = cell.format().toTableCellFormat();

    // 获取字体高度
    QTextCursor cellCursor = cell.firstCursorPosition();
    QFontMetrics fm(cellCursor.charFormat().font());
    int fontHeight = fm.height();

    // 计算总行高 = 字体高度 + 上下内边距
    int totalHeight = fontHeight + cellFormat.topPadding() + cellFormat.bottomPadding();

    return totalHeight;
}

//void TextEditor::exportToHtml()
//{

//}// 新增：导出HTML
bool TextEditor::saveRichTextToHtmlWithBase64(QTextEdit* textEdit, const QString& filePath)
{
    if (!textEdit) return false;

    QTextDocument* doc = textEdit->document();
    QString html = doc->toHtml();

    // 处理表格信息，为表格添加自定义属性，使用最新的映射信息（以毫米为单位）
    QRegularExpression tableRegex(R"(<table\s+[^>]*>)",
                               QRegularExpression::CaseInsensitiveOption |
                               QRegularExpression::DotMatchesEverythingOption);

    QTextCursor cursor = textEdit->textCursor();
    QVector<QTextTable*> tables;

    // 收集文档中的所有表格
    QTextFrame* rootFrame = doc->rootFrame();
    QTextFrame::iterator it;
    for (it = rootFrame->begin(); !it.atEnd(); ++it) {
        QTextFrame* childFrame = it.currentFrame();
        if (childFrame) {
            QTextTable* table = qobject_cast<QTextTable*>(childFrame);
            if (table) {
                tables.append(table);
            }
        }
    }

    // 为每个表格添加自定义属性，使用映射中的最新信息（以毫米为单位输出）
    int tableIndex = 0;
    QRegularExpressionMatchIterator tableMatches = tableRegex.globalMatch(html);
    while (tableMatches.hasNext() && tableIndex < tables.size()) {
        QRegularExpressionMatch match = tableMatches.next();
        QTextTable* table = tables[tableIndex++];

        if (!tableInfoMap.contains(table)) {
            qDebug() << "Warning: Table not found in info map, skipping...";
            continue;
        }

        const TableInfo &tableInfo = tableInfoMap[table];
        int rows = tableInfo.rows;
        int cols = tableInfo.columns;

        // 使用映射中的行高和列宽信息（直接使用毫米值）
        QString rowHeights = "";
        QString colWidths = "";

        // 输出行高（毫米）
        for (int i = 0; i < rows && i < tableInfo.rowHeights.size(); i++) {
            rowHeights += QString::number(tableInfo.rowHeights[i], 'f', 2) + ",";  // 保留2位小数
        }

        // 输出列宽（毫米）
        for (int j = 0; j < cols && j < tableInfo.columnWidths.size(); j++) {
            colWidths += QString::number(tableInfo.columnWidths[j], 'f', 2) + ",";  // 保留2位小数
        }

        // 移除最后的逗号
        if (!rowHeights.isEmpty()) rowHeights.chop(1);
        if (!colWidths.isEmpty()) colWidths.chop(1);

        // 构建带有自定义属性的表格标签（以毫米为单位）
        QString newTableTag = QString("<table data-rows=\"%1\" data-cols=\"%2\" data-rowheights=\"%3\" data-colwidths=\"%4\">")
                .arg(rows).arg(cols).arg(rowHeights).arg(colWidths);

        // 替换原始表格标签
        html.replace(match.capturedStart(), match.capturedLength(), newTableTag);

        qDebug() << "Exported table with" << rows << "rows," << cols << "columns using latest info from map (in mm):";
        qDebug() << "Row heights (mm):" << rowHeights;
        qDebug() << "Column widths (mm):" << colWidths;
    }

    // 处理图片，将图片转为Base64
    QRegularExpression imgRegex(R"(<img\s+[^>]*src=(["'])(.*?)\1[^>]*>)",
                               QRegularExpression::CaseInsensitiveOption |
                               QRegularExpression::DotMatchesEverythingOption);

    struct ImageReplacement {
        int start;
        int length;
        QString base64;
    };

    QVector<ImageReplacement> replacements;
    QRegularExpressionMatchIterator imgMatches = imgRegex.globalMatch(html);

    // 第一阶段：收集所有需要替换的图片信息
    while (imgMatches.hasNext()) {
        QRegularExpressionMatch match = imgMatches.next();
        QString src = match.captured(2);

        QVariant imageData = doc->resource(QTextDocument::ImageResource, QUrl(src));
        if (!imageData.isValid()) continue;

        QImage image = imageData.value<QImage>();
        if (image.isNull()) continue;

        // 获取图片格式
        QString format = "PNG"; // 默认格式
        if (src.contains(".jpg", Qt::CaseInsensitive) || src.contains(".jpeg", Qt::CaseInsensitive)) {
            format = "JPEG";
        } else if (src.contains(".png", Qt::CaseInsensitive)) {
            format = "PNG";
        } else if (src.contains(".bmp", Qt::CaseInsensitive)) {
            format = "BMP";
        }

        // 转换为Base64
        QByteArray byteArray;
        QBuffer buffer(&byteArray);
        buffer.open(QIODevice::WriteOnly);
        image.save(&buffer, format.toUtf8().constData());
        buffer.close();

        QString base64 = QString("data:image/%1;base64,%2")
                        .arg(format.toLower())
                        .arg(QString(byteArray.toBase64()));

        replacements.append({
            match.capturedStart(2),
            match.capturedLength(2),
            base64
        });
    }

    // 第二阶段：逆向替换(避免位置偏移)
    for (auto it = replacements.rbegin(); it != replacements.rend(); ++it) {
        html.replace(it->start, it->length, it->base64);
    }

    // 写入文件
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }

    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    stream << html;
    file.close();

    qDebug() << "HTML exported successfully with" << tableInfoMap.size() << "tables tracked in map (dimensions in mm)";
    return true;
}

// 新增：解析HTML中的图片和表格
// 修复后的 parseHtmlWithImagesAndTables 函数
QString TextEditor::parseHtmlWithImagesAndTables(const QString &htmlContent,
                                                const QString &outputImagePath,
                                                QVector<ImageInfo> &imageList,
                                                QVector<ParsedTableInfo> &tableList,
                                                int lineHeight)
{
    int actualLineHeight = lineHeight;
        if (textEdit) {
            QFontMetrics fm(textEdit->font());
            actualLineHeight = fm.height();
        }

    QTextDocument doc;
    doc.setHtml(htmlContent);

    QString plainText;
    QTextBlock block = doc.begin();
    int totalLines = 0;

    // 清空输出列表
    imageList.clear();
    tableList.clear();

    QVector<QPair<double, double>> imageAttributes; // 存储 (width, height)

    QRegularExpression imgRegex(R"(<img\s+[^>]*>)",
                               QRegularExpression::CaseInsensitiveOption |
                               QRegularExpression::DotMatchesEverythingOption);

    QRegularExpressionMatchIterator imgMatches = imgRegex.globalMatch(htmlContent);
    while (imgMatches.hasNext()) {
        QRegularExpressionMatch match = imgMatches.next();
        QString imgTag = match.captured(0);

        // 提取width属性
        QRegularExpression widthRegex(R"(width=(["']?)(\d+(?:\.\d+)?)\1)");
        QRegularExpressionMatch widthMatch = widthRegex.match(imgTag);

        // 提取height属性
        QRegularExpression heightRegex(R"(height=(["']?)(\d+(?:\.\d+)?)\1)");
        QRegularExpressionMatch heightMatch = heightRegex.match(imgTag);

        double width = 0;
        double height = 0;

        if (widthMatch.hasMatch()) {
            width = widthMatch.captured(2).toDouble();
        }

        if (heightMatch.hasMatch()) {
            height = heightMatch.captured(2).toDouble();
        }

        imageAttributes.append(QPair<double, double>(width, height));
        qDebug() << "Found image attributes - width:" << width << "height:" << height;
    }

    // 预先解析所有表格的自定义属性
    QVector<ParsedTableInfo> parsedTableAttributes;
    QRegularExpression tableAttrRegex(
        "<table[^>]*data-rows=\"(\\d+)\"[^>]*data-cols=\"(\\d+)\"[^>]*data-rowheights=\"([^\"]*)\"[^>]*data-colwidths=\"([^\"]*)\"[^>]*>",
        QRegularExpression::CaseInsensitiveOption | QRegularExpression::DotMatchesEverythingOption
    );

    QRegularExpressionMatchIterator tableMatches = tableAttrRegex.globalMatch(htmlContent);
    while (tableMatches.hasNext()) {
        QRegularExpressionMatch match = tableMatches.next();

        ParsedTableInfo tableAttr;
        tableAttr.rows = match.captured(1).toInt();
        tableAttr.columns = match.captured(2).toInt();

        // 解析行高（毫米）
        QString rowHeightsStr = match.captured(3);
        QStringList rowHeightList = rowHeightsStr.split(',', QString::SkipEmptyParts);
        tableAttr.rowHeights.clear();
        for (const QString& heightStr : rowHeightList) {
            tableAttr.rowHeights.append(heightStr.toDouble());
        }

        // 解析列宽（毫米）
        QString colWidthsStr = match.captured(4);
        QStringList colWidthList = colWidthsStr.split(',', QString::SkipEmptyParts);
        tableAttr.columnWidths.clear();
        for (const QString& widthStr : colWidthList) {
            tableAttr.columnWidths.append(widthStr.toDouble());
        }

        parsedTableAttributes.append(tableAttr);

        qDebug() << "Pre-parsed table attributes - rows:" << tableAttr.rows << "cols:" << tableAttr.columns;
        qDebug() << "Row heights (mm):" << rowHeightsStr;
        qDebug() << "Column widths (mm):" << colWidthsStr;
    }

    // 收集文档中的所有表格
    QVector<QTextTable*> allTables;
    QTextFrame* rootFrame = doc.rootFrame();
    QTextFrame::iterator frameIt;
    for (frameIt = rootFrame->begin(); !frameIt.atEnd(); ++frameIt) {
        QTextFrame* childFrame = frameIt.currentFrame();
        if (childFrame) {
            QTextTable* table = qobject_cast<QTextTable*>(childFrame);
            if (table) {
                allTables.append(table);
            }
        }
    }

    qDebug() << "Found" << allTables.size() << "tables in document";
    qDebug() << "Found" << parsedTableAttributes.size() << "table attributes in HTML";

    QSet<QTextTable*> processedTables; // 跟踪已处理的表格
    int currentTableIndex = 0; // 当前处理的表格索引

    while (block.isValid()) {
        QTextBlock::iterator it;
        bool blockHasTable = false;

        // 检查当前块是否是表格的一部分
        QTextTable* table = nullptr;
        QTextCursor cursor(&doc);
        cursor.setPosition(block.position());
        table = cursor.currentTable();

        if (table && !processedTables.contains(table)) {
            blockHasTable = true;
            processedTables.insert(table);

            ParsedTableInfo tableInfo;
            tableInfo.startLineNumber = totalLines;
            tableInfo.rows = table->rows();
            tableInfo.columns = table->columns();

            // 初始化单元格内容数组
            tableInfo.cellContents.resize(tableInfo.rows);
            for (int i = 0; i < tableInfo.rows; i++) {
                tableInfo.cellContents[i].resize(tableInfo.columns);
            }

            // 尝试匹配对应的表格属性
            bool foundMatchingAttributes = false;
            if (currentTableIndex < parsedTableAttributes.size()) {
                const ParsedTableInfo& attrs = parsedTableAttributes[currentTableIndex];

                // 验证是否匹配当前表格的尺寸
                if (attrs.rows == tableInfo.rows && attrs.columns == tableInfo.columns) {
                    foundMatchingAttributes = true;
                    tableInfo.rowHeights = attrs.rowHeights;
                    tableInfo.columnWidths = attrs.columnWidths;

                    qDebug() << "Matched table" << currentTableIndex << "with custom attributes";
                } else {
                    qDebug() << "Table" << currentTableIndex << "dimensions mismatch - expected:"
                             << attrs.rows << "x" << attrs.columns
                             << "actual:" << tableInfo.rows << "x" << tableInfo.columns;
                }
            }

            // 如果没有找到匹配的属性，使用默认值
            if (!foundMatchingAttributes) {
                qDebug() << "Using default values for table" << currentTableIndex;
                tableInfo.rowHeights.resize(tableInfo.rows);
                tableInfo.columnWidths.resize(tableInfo.columns);

                // 设置默认值（毫米）
                for (int i = 0; i < tableInfo.rows; i++) {
                    tableInfo.rowHeights[i] = 7.9; // 默认行高7.9mm
                }
                for (int j = 0; j < tableInfo.columns; j++) {
                    tableInfo.columnWidths[j] = 26.0; // 默认列宽26mm
                }
            }

            // 提取单元格内容
            for (int row = 0; row < tableInfo.rows; row++) {
                for (int col = 0; col < tableInfo.columns; col++) {
                    QTextTableCell cell = table->cellAt(row, col);
                    if (cell.isValid()) {
                        // 获取单元格的纯文本内容
                        QTextCursor cellCursor = cell.firstCursorPosition();
                        cellCursor.setPosition(cell.lastPosition(), QTextCursor::KeepAnchor);
                        QString cellText = cellCursor.selectedText();

                        // 清理文本（移除特殊字符）
                        cellText = cellText.replace(QChar(0x2029), '\n'); // 段落分隔符
                        cellText = cellText.replace(QChar(0x2028), '\n'); // 行分隔符
                        cellText = cellText.trimmed();

                        tableInfo.cellContents[row][col] = cellText;
                    }
                }
            }

            tableList.append(tableInfo);
            currentTableIndex++;

            qDebug() << "Parsed table" << (currentTableIndex-1) << "at line" << totalLines
                     << "with" << tableInfo.rows << "rows and" << tableInfo.columns << "columns";

            // 表格占用的行数等于行数
//            editTotalLines += tableInfo.rows * 2;
            totalLines += tableInfo.rows * 2;
//            totalLines++;
        }
        else if (table) {
            // 如果当前块属于已处理的表格，跳过它，不添加到plainText中
            blockHasTable = true;
            qDebug() << "Skipping table content block at position" << block.position();
        }
        else{
            for (it = block.begin(); !it.atEnd(); ++it) {
            QTextFragment fragment = it.fragment();

            if (!fragment.isValid())
                continue;

            QTextCharFormat format = fragment.charFormat();

            // 处理图片
            if (format.isImageFormat()) {
                QTextImageFormat imageFormat = format.toImageFormat();
                QString name = imageFormat.name();

                // 判断是否是 Base64 图片
                if (name.startsWith("data:image/")) {
                    QUrl url(name);
                    QByteArray imageData = QByteArray::fromBase64(url.toString().split(",").last().toUtf8());

                    QImage image;
                    if (image.loadFromData(imageData)) {
                        // 保存图片到文件
                        QString imageFileName = QString("image_%1.png").arg(imageList.size() + 1);
                        QString fullImagePath = outputImagePath + "/" + imageFileName;

                        if (image.save(fullImagePath, 0)) {
                            ImageInfo info;
                            info.lineNumber = totalLines;
                            info.width = imageFormat.width();
                            info.height = imageFormat.height();
                            info.imagePath = fullImagePath;
                            imageList.append(info);

                            qDebug() << "Parsed image at line" << totalLines << "saved to" << fullImagePath;
                        }
                    }
                }
                // 处理普通文件路径图片
                else if (QFile::exists(name)) {
                    ImageInfo info;
                    info.lineNumber = totalLines;
                    info.width = imageFormat.width();
                    info.height = imageFormat.height();
                    info.imagePath = name;
                    imageList.append(info);

                    qDebug() << "Parsed image at line" << totalLines << "path:" << name << "imageformat" << imageFormat.height();
                }

                // 图片通常占用一行或多行
                qDebug() << "info.lineNumber: " << totalLines;
    //                int imageHeightInLines = qMax(1, (int)ceil(imageFormat.height() / actualLineHeight));
    //                totalLines += imageHeightInLines;
                totalLines++;
    //                qDebug() << "image totallines: " << imageHeightInLines;
            }
            // 处理普通文本
            else {
                QString text = fragment.text();
                plainText += text + "\n";

                // 计算文本占用的行数
                int textLines = text.count('\n') + (text.isEmpty() ? 0 : 1);
                if (!blockHasTable) {
                    totalLines += textLines;
                }
            }
        }

    }



//        if (!blockHasTable) {
//            // 如果不是表格块，正常处理换行
//            if (block.text().isEmpty()) {
//                totalLines += 1; // 空行
//            }
//        }

        block = block.next();
    }

    qDebug() << "Total parsed images:" << imageList.size();
    qDebug() << "Total parsed tables:" << tableList.size();
    qDebug() << "Expected tables from HTML attributes:" << parsedTableAttributes.size();
    qDebug() << "Actual tables found in document:" << allTables.size();
    qDebug() << "Total lines:" << totalLines;

    // 验证结果
    if (tableList.size() != allTables.size()) {
        qDebug() << "Warning: Mismatch between parsed tables and actual tables in document!";
    }
    qDebug() << "plaintext: " << plainText << "  " <<actualLineHeight;

    exportToImage("output.png");

    displayParsedContent(plainText, imageList, tableList);
    return plainText;
}

bool TextEditor::exportToImage(const QString &outputPath,
                              const QString &imageFormat,
                              const QColor &backgroundColor,
                              int dpi,
                              double scaleFactor)
{
    if (!textEdit) {
        qDebug() << "TextEdit is null";
        return false;
    }

    // 获取文档
    QTextDocument *document = textEdit->document();
    if (!document) {
        qDebug() << "Document is null";
        return false;
    }

    // 设置文档的页面大小和边距
    QSizeF originalSize = document->pageSize();

    // 如果没有设置页面大小，使用默认的A4大小
    if (originalSize.isEmpty()) {
        // A4大小：210mm x 297mm，转换为像素 (假设96 DPI)
        qreal mmToPixel = dpi / 25.4; // 1英寸 = 25.4毫米
        QSizeF a4Size(210 * mmToPixel, 297 * mmToPixel);
        document->setPageSize(a4Size);
    }

    // 获取文档的实际内容大小
    QSizeF documentSize = document->size();

    // 应用缩放因子
    int imageWidth = qRound(documentSize.width() * scaleFactor);
    int imageHeight = qRound(documentSize.height() * scaleFactor);

    // 创建图片
    QImage image(imageWidth, imageHeight, QImage::Format_ARGB32);
    image.fill(backgroundColor);

    // 设置DPI
    image.setDotsPerMeterX(dpi * 39.3701); // 1英寸 = 39.3701 厘米
    image.setDotsPerMeterY(dpi * 39.3701);

    // 创建绘制器
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    // 应用缩放
    if (scaleFactor != 1.0) {
        painter.scale(scaleFactor, scaleFactor);
    }

    // 绘制文档内容
    document->drawContents(&painter);

    painter.end();

    // 恢复原始页面大小
    document->setPageSize(originalSize);

    // 保存图片
    bool success = image.save(outputPath, imageFormat.toUtf8().constData());

    if (success) {
        qDebug() << "Successfully exported to image:" << outputPath;
        qDebug() << "Image size:" << imageWidth << "x" << imageHeight;
        qDebug() << "Format:" << imageFormat;
        qDebug() << "DPI:" << dpi;
    } else {
        qDebug() << "Failed to export to image:" << outputPath;
    }

    return success;
}

void TextEditor::displayParsedContent(const QString &plainText,
                                     const QVector<ImageInfo> &imageList,
                                     const QVector<ParsedTableInfo> &tableList)
{
    if (!textEdit) {
        qDebug() << "TextEdit is null";
        return;
    }

    // 清理旧的表格信息映射
    tableInfoMap.clear();

    // 1. 先设置所有文本内容
    textEdit->clear();
    textEdit->setPlainText(plainText);

    // 2. 获取文档
    QTextDocument *document = textEdit->document();

    // 3. 插入图片 - 移动光标到指定行首
    for (const ImageInfo &imageInfo : imageList) {
        QTextCursor cursor = moveToLineStart(document, imageInfo.lineNumber);
        if (!cursor.isNull()) {
            insertImageAtCursor(cursor, imageInfo);
        }
    }

    // 4. 插入表格 - 移动光标到指定行首
    for (const ParsedTableInfo &tableInfo : tableList) {
        QTextCursor cursor = moveToLineStart(document, tableInfo.startLineNumber);
        if (!cursor.isNull()) {
            insertTableAtCursor(cursor, tableInfo);
        }
    }
}

// 新增函数：将光标移动到指定行的开头
QTextCursor TextEditor::moveToLineStart(QTextDocument *document, int lineNumber)
{
    QTextCursor cursor(document);

    // 移动到文档开头
    cursor.movePosition(QTextCursor::Start);

    // 向下移动到指定行
    for (int i = 0; i < lineNumber && !cursor.atEnd(); ++i) {
        cursor.movePosition(QTextCursor::Down);
    }

    // 移动到行首
    cursor.movePosition(QTextCursor::StartOfLine);

    return cursor;
}

// 修改insertImageAtCursor函数，在行首插入图片
void TextEditor::insertImageAtCursor(QTextCursor &cursor, const ImageInfo &imageInfo)
{
    QString imagePath = imageInfo.imagePath;

    // 检查图片文件是否存在
    if (!QFile::exists(imagePath)) {
        qDebug() << "Image file not found:" << imagePath;
        return;
    }

    // 加载图片
    QPixmap pixmap(imagePath);
    if (pixmap.isNull()) {
        qDebug() << "Failed to load image:" << imagePath;
        return;
    }

    // 移动到行首
    cursor.movePosition(QTextCursor::StartOfLine);

    // 创建图片格式
    QTextImageFormat imageFormat;
    QString resourceName = QString("image_%1_%2").arg(imageInfo.lineNumber).arg(QTime::currentTime().msecsSinceStartOfDay());
    imageFormat.setName(resourceName);

    // 设置图片大小
    int maxWidth = textEdit->width() * 0.7;
    if (pixmap.width() > maxWidth) {
        double ratio = (double)maxWidth / pixmap.width();
        imageFormat.setWidth(maxWidth);
        imageFormat.setHeight(pixmap.height() * ratio);
    } else {
        imageFormat.setWidth(pixmap.width());
        imageFormat.setHeight(pixmap.height());
    }

    // 添加图片资源
    textEdit->document()->addResource(QTextDocument::ImageResource,
                                     QUrl(resourceName),
                                     QVariant(pixmap));

    // 在行首插入图片
    cursor.insertImage(imageFormat);
    cursor.insertBlock();

    qDebug() << "Image inserted at line" << imageInfo.lineNumber << ":" << imagePath;
}

int TextEditor::mmToPixels(double mm) {
    // 96 DPI: 1英寸 = 25.4毫米 = 96像素
    // 所以 1毫米 = 96/25.4 像素 ≈ 3.78像素
    return static_cast<int>(mm * 96.0 / 25.4);
}

// 修改insertTableAtCursor函数，在行首插入表格
void TextEditor::insertTableAtCursor(QTextCursor &cursor, const ParsedTableInfo &tableInfo)
{
    if (tableInfo.cellContents.isEmpty()) {
        return;
    }

    // 移动到行首
    cursor.movePosition(QTextCursor::StartOfLine);

    int rows = tableInfo.cellContents.size();
    int columns = tableInfo.cellContents[0].size();

    // 创建表格格式
    QTextTableFormat tableFormat;
    tableFormat.setCellPadding(4);
    tableFormat.setCellSpacing(0);
    tableFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
    tableFormat.setBorder(1);
    tableFormat.setAlignment(Qt::AlignLeft);

    // 设置列宽
    QVector<QTextLength> columnWidths;
    if (!tableInfo.columnWidths.isEmpty()) {
        for (double width : tableInfo.columnWidths) {
            columnWidths.append(QTextLength(QTextLength::FixedLength, mmToPixels(width)));
        }
    } else {
        // 默认等宽
        double defaultWidth = 100.0 / columns;
        for (int i = 0; i < columns; ++i) {
            columnWidths.append(QTextLength(QTextLength::PercentageLength, defaultWidth));
        }
    }
    tableFormat.setColumnWidthConstraints(columnWidths);

    // 插入表格
    QTextTable *table = cursor.insertTable(rows, columns, tableFormat);

    // 填充表格数据
    for (int row = 0; row < tableInfo.rows && row < tableInfo.cellContents.size(); ++row) {
            const QVector<QString> &rowData = tableInfo.cellContents[row];
            for (int col = 0; col < tableInfo.columns && col < rowData.size(); ++col) {
                QTextTableCell cell = table->cellAt(row, col);
                if (cell.isValid()) {
                    QTextCursor cellCursor = cell.firstCursorPosition();
                    cellCursor.insertText(rowData[col]);
                }
            }
        }
    // 存储表格信息到映射中
    TableInfo info;
    info.columnWidths = tableInfo.columnWidths;
    tableInfoMap[table] = info;

    qDebug() << "Table inserted at line" << tableInfo.startLineNumber
             << "with" << rows << "rows and" << columns << "columns";
}


